package top.buaarobot.webserver.service;

import top.buaarobot.webserver.domain.SystemNotice;
import top.buaarobot.webserver.domain.User;
import top.buaarobot.webserver.repository.SystemNoticeRepository;
import top.buaarobot.webserver.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SystemNoticeServiceImpl implements SystemNoticeService {
    @Autowired
    private SystemNoticeRepository systemNoticeRepository;
    @Autowired
    private UserRepository userRepository;

    @Override
    public Iterable<SystemNotice> Get(int userId) {
        return AddOwner(this.systemNoticeRepository.searchByUserId(userId));
    }

    @Override
    public String Add(SystemNotice systemNotice) {
        this.systemNoticeRepository.saveAndFlush(systemNotice);
        return "Success";
    }

    @Override
    public String Delete(int id) {
        systemNoticeRepository.deleteById(id);
        return "Success";
    }

    @Override
    public String Clear(int userId) {
        systemNoticeRepository.deleteAllByUserId(userId);
        return "Success";
    }

    @Override
    public String Read(int id) {
        SystemNotice tmp = systemNoticeRepository.findById(id).get();
        tmp.setIsRead(1);
        systemNoticeRepository.saveAndFlush(tmp);
        return "Success";
    }

    private Iterable<SystemNotice> AddOwner(Iterable<SystemNotice> notices){
        for(SystemNotice notice:notices){
            if(notice.getOwnerId()==-1) {
                notice.setOwner("匿名用户");
            }else{
                User owner = userRepository.findById(notice.getOwnerId()).get();
                notice.setOwner(owner.getNickname());
            }
        }
        return notices;
    }
}
